package ru.viadent.web.controllers;

import com.google.gson.Gson;
import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import ru.viadent.web.AppSettings;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: Владислав
 * Date: 4/2/13
 * Time: 11:55 PM
 * To change this template use File | Settings | File Templates.
 */

@Controller
public class IndexController {

    @Autowired
    ReCaptchaImpl reCaptcha;

    @Autowired
    JavaMailSender javaMailSender;

    @RequestMapping(value = {
            "/",
            "/contacts",
            "/articles",
            "/discounts",
            "/job",
            "/price",
            "/prosthetics",
            "/question-ask",
            "/reviews",
            "/services",
            "/share",
            "articles/cerec3d",
            "articles/cerecac"}, method = RequestMethod.GET)
    public String index(Model model, HttpServletRequest request){
        String path = request.getServletPath();
        /*if(path.startsWith("/")){
            path = path.substring(1);
        }
        if(path.endsWith("/")){
            path = path.substring(0, path.length() - 1);
        }*/
        path = path.replaceAll("(^\\/)|(\\/$)", "");
        path = path.replaceAll("(\\/)", ".");
        if ("".equals(path)){
            return "index";
        }
        return path;
    }

    @RequestMapping(value = "/feedback", method = RequestMethod.POST)
    public String feedback(@RequestParam(value = "name") String name,
                                       @RequestParam(value = "phone") String phone,
                                       @RequestParam(value = "email") String email,
                                       @RequestParam(value = "message") String message,
                                       Model model){



        /*String from = AppSettings.getInstance().getMailFrom();
        String to = AppSettings.getInstance().getMailTo();*/
        String from = "no-reply@via-dent.ru";
        String to = "v.i.a.dent@mail.ru";
        String subject = "Вопрос от " + name;
        String text = "<html><body>" +
                "<table border=\"0\" cellspacing=\"0\" cellpadding=\"5\">" +
                "<tr><td valign=\"top\">Имя</td><td width=\"300\">" + name + "</td></tr>" +
                "<tr><td valign=\"top\">Телефон</td><td width=\"300\">" + phone + "</td></tr>" +
                "<tr><td valign=\"top\">E-mail</td><td width=\"300\">" + email + "</td></tr>" +
                "<tr><td valign=\"top\">Сообщение</td><td width=\"300\">" + message + "</td></tr>" +
                "</table>" +
                "</body></html>";

        sendMail(from, to, subject, text);
        return "index";
    }

    private void sendMail(String from, String to, String subject, String text) {
        MimeMessage mailMessage = javaMailSender.createMimeMessage();
        try {
            mailMessage.setFrom(new InternetAddress(from));
            mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            mailMessage.setContent(text, "text/html;charset=UTF-8");
            mailMessage.setSubject(subject);
        } catch (MessagingException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        javaMailSender.send(mailMessage);
    }

    @RequestMapping(value = "/appointments", method = RequestMethod.POST)
    public String appointments(@RequestParam(value = "name") String name,
                                           @RequestParam(value = "phone") String phone,
                                           @RequestParam(value = "email") String email,
                                           @RequestParam(value = "timestamp") String timestamp,
                                           @RequestParam(value = "message") String message,
                                           HttpServletRequest request,
                                           Model model){
        //ReCaptchaResponse response = reCaptcha.checkAnswer(request.getRemoteAddr(), request.getParameter("recaptcha_challenge_field"), request.getParameter("recaptcha_response_field"));
        //if(response.isValid()){
        boolean isValidReCaptcha = false;
        try {
            isValidReCaptcha = isValidReCaptcha();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(isValidReCaptcha){
            /*String from = AppSettings.getInstance().getMailFrom();
            String to = AppSettings.getInstance().getMailTo();*/
            /*String from = "no-reply@via-dent.ru";
            String to = "v.i.a.dent@mail.ru";*/
            String from = "test@via-dent.ru";
            String to = "vladbrkwide@gmail.com";
            String subject = "Запись на прием " + name;
            String text = "<html><body>" +
                    "<table border=\"0\" cellspacing=\"0\" cellpadding=\"5\">" +
                    "<tr><td valign=\"top\">Имя</td><td width=\"300\">" + name +"</td></tr>" +
                    "<tr><td valign=\"top\">Телефон</td><td width=\"300\">" + phone + "</td></tr>" +
                    "<tr><td valign=\"top\">E-mail</td><td width=\"300\">" + email + "</td></tr>" +
                    "<tr><td valign=\"top\">Планируемая дата и время визита</td><td width=\"300\">" + timestamp + "</td></tr>" +
                    "<tr><td valign=\"top\">Цель визита</td><td width=\"300\">" + message + "</td></tr>" +
                    "</table>" +
                    "</body></html>";

            sendMail(from, to, subject, text);
        }
        return "index";

    }

    @RequestMapping(value = "/image/coupon")
    public void imageCoupon(HttpServletResponse response){
        InputStream coupon = getClass().getResourceAsStream("/coupon_V.I.A.DENT.png");
        response.setHeader("Content-Type", "image/png;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=\"coupon_V.I.A.DENT.png\"");
        try {
            response.getOutputStream().write(IOUtils.toByteArray(coupon));
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    @RequestMapping(value = "/favicon.ico")
    public void favicon(HttpServletResponse response){
        InputStream coupon = getClass().getResourceAsStream("/favicon.ico");
        response.setHeader("Content-Type", "image/vnd.microsoft.icon;charset=UTF-8");
        try {
            response.getOutputStream().write(IOUtils.toByteArray(coupon));
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    private boolean isValidReCaptcha() throws Exception {

        String url = "http://www.google.com/recaptcha/api/siteverify?secret=6Lf7YQITAAAAAMxdyqbVT3QYHFRwXat7ZAeqeqjJ&response=g-recaptcha-response";

        URL obj = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        connection.setRequestMethod("GET");

        //add request header
        //con.setRequestProperty("User-Agent", "Mozilla/5.0");

        //int responseCode = connection.getResponseCode();

        BufferedReader in = new BufferedReader(
                new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        response.toString();

        Gson gson = new Gson();
        ru.viadent.web.controllers.ReCaptchaResponse reCaptchaResponse = gson.fromJson(response.toString(), ru.viadent.web.controllers.ReCaptchaResponse.class);
        return BooleanUtils.isTrue(reCaptchaResponse.getSuccess());
    }

}
